<template>
  <div class="job-management">
    <el-card>
      <div slot="header">
        <span>招聘信息管理</span>
        <el-button type="primary" @click="showJobDialog" style="float: right">
          发布新职位
        </el-button>
      </div>
      
      <el-table :data="jobList" v-loading="loading">
        <el-table-column prop="jobName" label="职位名称"></el-table-column>
        <el-table-column prop="salaryTreatment" label="薪资待遇"></el-table-column>
        <el-table-column prop="workTime" label="工作时间"></el-table-column>
        <el-table-column prop="location" label="工作地点"></el-table-column>
        <el-table-column prop="requirement" label="岗位要求"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ scope.row.status === '1' ? '已发布' : '未发布' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button type="text" @click="editJob(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteJob(scope.row.id)">删除</el-button>
            <el-button type="text" @click="viewApplications(scope.row)">查看申请</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 发布/编辑职位对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="jobDialogVisible">
      <el-form :model="jobForm" :rules="rules" ref="jobForm" label-width="100px">
        <el-form-item label="职位名称" prop="jobName">
          <el-input v-model="jobForm.jobName"></el-input>
        </el-form-item>
        <el-form-item label="薪资待遇" prop="salaryTreatment">
          <el-input v-model="jobForm.salaryTreatment"></el-input>
        </el-form-item>
        <el-form-item label="工作时间" prop="workTime">
          <el-input v-model="jobForm.workTime"></el-input>
        </el-form-item>
        <el-form-item label="工作地点" prop="location">
          <el-input v-model="jobForm.location"></el-input>
        </el-form-item>
        <el-form-item label="岗位要求" prop="requirement">
          <el-input type="textarea" v-model="jobForm.requirement" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="职位描述" prop="detail">
          <el-input type="textarea" v-model="jobForm.detail" rows="4"></el-input>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-radio-group v-model="jobForm.status">
            <el-radio label="1">已发布</el-radio>
            <el-radio label="2">未发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="jobDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitJob">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加查看应聘申请的对话框 -->
    <el-dialog title="应聘申请列表" :visible.sync="applicationDialogVisible" width="80%">
      <el-table :data="applicationList" v-loading="applicationLoading">
        <el-table-column prop="userName" label="应聘人"></el-table-column>
        <el-table-column prop="createTime" label="申请时间">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            {{ getStatusText(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button 
              type="success" 
              size="small" 
              @click="handleApplication(scope.row.id, 2)"
              :disabled="scope.row.status !== 1">
              通过
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleApplication(scope.row.id, 3)"
              :disabled="scope.row.status !== 1">
              拒绝
            </el-button>
            <el-button 
              type="warning" 
              size="small" 
              @click="deleteApplication(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 查看简历的对话框 -->
    <el-dialog title="应聘简历" :visible.sync="resumeDialogVisible" width="60%">
      <div v-if="currentResume">
        <h3>基本信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="姓名">{{ currentResume.studentName }}</el-descriptions-item>
          <el-descriptions-item label="性别">{{ currentResume.gender }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ currentResume.age }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentResume.phone }}</el-descriptions-item>
          <el-descriptions-item label="电子邮箱">{{ currentResume.email }}</el-descriptions-item>
        </el-descriptions>
        
        <h3>个人简介</h3>
        <div class="resume-content">{{ currentResume.introduction }}</div>
        
        <h3>教育经历</h3>
        <div class="resume-content">{{ currentResume.education }}</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'JobManagement',
  data() {
    return {
      jobList: [],
      loading: false,
      jobDialogVisible: false,
      dialogTitle: '发布新职位',
      currentJobId: null,
      jobForm: {
        jobName: '',
        salaryTreatment: '',
        workTime: '',
        location: '',
        requirement: '',
        detail: '',
        status: '1'  // 默认为已发布状态
      },
      rules: {
        jobName: [{ required: true, message: '请输入职位名称', trigger: 'blur' }],
        salaryTreatment: [{ required: true, message: '请输入薪资待遇', trigger: 'blur' }],
        workTime: [{ required: true, message: '请输入工作时间', trigger: 'blur' }],
        location: [{ required: true, message: '请输入工作地点', trigger: 'blur' }],
        requirement: [{ required: true, message: '请输入岗位要求', trigger: 'blur' }],
        detail: [{ required: true, message: '请输入职位描述', trigger: 'blur' }]
      },
      applicationDialogVisible: false,
      resumeDialogVisible: false,
      applicationList: [],
      applicationLoading: false,
      currentResume: null
    }
  },
  methods: {
    async fetchJobs() {
      try {
        this.loading = true
        const username = localStorage.getItem('username')
        const response = await this.$axios.get('/jobseekerJobRelation/list', {
          params: {
            username: username
          }
        })
        if (response.data.code === 200) {
          this.jobList = response.data.data || []
        } else {
          this.$message.error(response.data.msg || '获取职位列表失败')
        }
      } catch (error) {
        this.$message.error('获取职位列表失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    
    showJobDialog() {
      this.dialogTitle = '发布新职位'
      this.currentJobId = null
      this.jobForm = {
        jobName: '',
        salaryTreatment: '',
        workTime: '',
        location: '',
        requirement: '',
        detail: '',
        status: '1'  // 新职位默认为已发布状态
      }
      this.jobDialogVisible = true
    },
    
    editJob(row) {
      this.dialogTitle = '编辑职位'
      this.currentJobId = row.id
      this.jobForm = {
        jobName: row.jobName,
        salaryTreatment: row.salaryTreatment,
        workTime: row.workTime,
        location: row.location,
        requirement: row.requirement,
        detail: row.detail,
        status: row.status || '1'  // 如果没有状态，默认为已发布
      }
      this.jobDialogVisible = true
    },
    
    async submitJob() {
      try {
        const valid = await this.$refs.jobForm.validate()
        if (valid) {
          // 根据是否有 currentJobId 来判断是编辑还是新增
          const url = this.currentJobId ? 
            '/jobInfo/edit' :  // 修改为编辑接口
            '/jobInfo/add'    // 修改为添加接口
          
          const jobData = {
            ...this.jobForm,
            username: localStorage.getItem('username')
          }

          // 如果是编辑模式，添加 id
          if (this.currentJobId) {
            jobData.id = this.currentJobId
          }
          
          const response = await this.$axios.post(url, jobData)
          
          if (response.data.code === 200) {
            this.$message.success(this.currentJobId ? '更新成功' : '发布成功')
            this.jobDialogVisible = false
            this.fetchJobs()
          } else {
            this.$message.error(response.data.msg || '操作失败')
          }
        }
      } catch (error) {
        this.$message.error('操作失败：' + (error.message || '未知错误'))
      }
    },
    
    async deleteJob(id) {
      try {
        await this.$confirm('确定要删除这个职位吗？', '提示', {
          type: 'warning'
        })
        
        // 修改删除接口路径
        const response = await this.$axios.delete(`/jobInfo/delete/${id}`)
        
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          this.fetchJobs()
        } else {
          this.$message.error(response.data.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      }
    },
    
    async viewApplications(row) {
      this.currentJobId = row.id
      this.applicationDialogVisible = true
      await this.fetchApplications()
    },
    
    async fetchApplications() {
      try {
        this.applicationLoading = true
        const username = localStorage.getItem('username')
        // 修改为新的接口路径
        const response = await this.$axios.get(`/jobseekerJobRelation/list/ByJobseekerJobRelation`, {
          params: {
            username: username,
            jobId: this.currentJobId
          }
        })
        if (response.data.code === 200) {
          this.applicationList = response.data.data || []
        } else {
          this.$message.error(response.data.msg || '获取申请列表失败')
        }
      } catch (error) {
        this.$message.error('获取申请列表失败：' + error.message)
      } finally {
        this.applicationLoading = false
      }
    },
    
    async handleApplication(applyId, status) {
      try {
        const response = await this.$axios.post('/jobseekerJobRelation/edit', {
          id: applyId,
          status: status
        })
        
        if (response.data.code === 200) {
          this.$message.success(status === 2 ? '已通过申请' : '已拒绝申请')
          await this.fetchApplications()
        } else {
          this.$message.error(response.data.msg || '操作失败')
        }
      } catch (error) {
        this.$message.error('操作失败：' + error.message)
      }
    },
    
    async deleteApplication(id) {
      try {
        await this.$confirm('确定要删除这条申请记录吗？', '提示', {
          type: 'warning'
        })
        
        const response = await this.$axios.delete(`/jobseekerJobRelation/delete/${id}`)
        
        if (response.data.code === 200) {
          this.$message.success('删除成功')
          await this.fetchApplications()
        } else {
          this.$message.error(response.data.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败：' + error.message)
        }
      }
    },
    
    async viewResume(application) {
      this.currentResume = application
      this.resumeDialogVisible = true
    },
    
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },
    
    getStatusText(status) {
      const statusMap = {
        1: '待处理',
        2: '已通过',
        3: '已拒绝'
      }
      return statusMap[status] || '未知状态'
    }
  },
  created() {
    this.fetchJobs()
  }
}
</script>

<style scoped>
.job-management {
  padding: 20px;
}

.resume-content {
  padding: 10px;
  margin: 10px 0;
  background-color: #f8f8f8;
  border-radius: 4px;
  line-height: 1.6;
}

h3 {
  margin: 20px 0 10px;
  color: #333;
}
</style> 